<template>
  <div class="role-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">角色管理</h1>
        <p class="page-description">管理系统角色和权限分配</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="handleAdd">
          新增角色
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-form">
        <el-input
          v-model="searchForm.keyword"
          placeholder="搜索角色名称或编码..."
          :prefix-icon="Search"
          clearable
          class="search-input"
          @input="handleSearch"
        />
        <el-select
          v-model="searchForm.status"
          placeholder="角色状态"
          clearable
          class="status-select"
          @change="handleSearch"
        >
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
        <el-button :icon="Refresh" @click="handleRefresh">刷新</el-button>
      </div>
    </div>

    <!-- 角色表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        :loading="loading"
        stripe
        class="role-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" min-width="150" />
        <el-table-column prop="code" label="角色编码" min-width="150" />
        <el-table-column prop="description" label="角色描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="权限数量" width="100">
          <template #default="{ row }">
            <el-tag type="info" size="small">
              {{ row.permissionCount || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <TableActionDropdown
              :actions="getRoleActionList(row)"
              :row="row"
              @action="handleRoleAction"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 角色详情/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
        class="role-form"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="roleForm.name"
            placeholder="请输入角色名称"
            :disabled="dialogMode === 'view'"
          />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input
            v-model="roleForm.code"
            placeholder="请输入角色编码"
            :disabled="dialogMode === 'view' || dialogMode === 'edit'"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
            :disabled="dialogMode === 'view'"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status" :disabled="dialogMode === 'view'">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer v-if="dialogMode !== 'view'">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ dialogMode === 'add' ? '创建' : '保存' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="分配权限"
      width="600px"
      :close-on-click-modal="false"
      @closed="handlePermissionDialogClosed"
    >
      <div class="permission-assignment">
        <div class="role-info">
          <h4>角色：{{ currentRole?.name }}</h4>
          <p>{{ currentRole?.description }}</p>
        </div>
        
        <el-tree
          ref="permissionTreeRef"
          :data="permissionTreeData"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedPermissions"
          class="permission-tree"
        >
          <template #default="{ node, data }">
            <div class="tree-node">
              <el-icon v-if="data.icon">
                <component :is="getIconComponent(data.icon)" />
              </el-icon>
              <span class="node-label">{{ data.name }}</span>
              <el-tag size="small" :type="getPermissionTypeTag(data.type)">
                {{ getPermissionTypeText(data.type) }}
              </el-tag>
            </div>
          </template>
        </el-tree>
      </div>
      
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePermissions" :loading="permissionLoading">
          保存权限
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getIconComponent } from '@/utils/iconMap'
import { roleAPI, rolePermissionAPI } from '@/api/role'
import { permissionAPI } from '@/api/permission'
import {
  Plus, Search, Refresh, View, Edit, Delete, Key
} from '@element-plus/icons-vue'
import TableActionDropdown from '@/components/TableActionDropdown.vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const permissionLoading = ref(false)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const dialogMode = ref('add')
const roleFormRef = ref()
const permissionTreeRef = ref()
const selectedRoles = ref([])
const currentRole = ref(null)
const checkedPermissions = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 角色表单
const roleForm = reactive({
  id: null,
  name: '',
  code: '',
  description: '',
  status: 1
})

// 表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ]
}

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 表格数据
const tableData = ref([])

// 权限树数据
const permissionTreeData = ref([])

// 计算属性
const dialogTitle = computed(() => {
  const titles = {
    add: '新增角色',
    edit: '编辑角色',
    view: '查看角色'
  }
  return titles[dialogMode.value]
})

// 获取权限类型标签
const getPermissionTypeTag = (type) => {
  const types = {
    1: 'primary',  // 菜单
    2: 'success',  // 按钮
    3: 'warning'   // API
  }
  return types[type] || 'info'
}

// 获取权限类型文本
const getPermissionTypeText = (type) => {
  const types = {
    1: '菜单',
    2: '按钮',
    3: 'API'
  }
  return types[type] || '未知'
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  loadTableData()
}

// 刷新数据
const handleRefresh = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  pagination.page = 1
  loadTableData()
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    const response = await roleAPI.getRoles({
      pageNum: pagination.page,
      pageSize: pagination.size,
      keyword: searchForm.keyword,
      status: searchForm.status
    })
    
    if (response.success) {
      tableData.value = response.data.records || []
      pagination.total = response.data.total || 0
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error(response.message || '加载数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载权限树数据
const loadPermissionTree = async () => {
  try {
    const response = await permissionAPI.getAllPermissionTree()
    if (response.success) {
      permissionTreeData.value = response.data || []
    }
  } catch (error) {
    console.error('加载权限树失败:', error)
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadTableData()
}

const handlePageChange = (page) => {
  pagination.page = page
  loadTableData()
}

// 选择变化处理
const handleSelectionChange = (selection) => {
  selectedRoles.value = selection
}

// 新增角色
const handleAdd = () => {
  dialogMode.value = 'add'
  resetRoleForm()
  dialogVisible.value = true
}

// 查看角色
const handleView = (row) => {
  dialogMode.value = 'view'
  fillRoleForm(row)
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  dialogMode.value = 'edit'
  fillRoleForm(row)
  dialogVisible.value = true
}

// 删除角色
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await roleAPI.deleteRole(row.id)
    if (response.success) {
      ElMessage.success('删除成功')
      loadTableData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分配权限
const handleAssignPermission = async (row) => {
  currentRole.value = row
  
  // 先清空之前的选中状态
  checkedPermissions.value = []
  
  // 如果树组件已经存在，先清除其选中状态
  if (permissionTreeRef.value) {
    permissionTreeRef.value.setCheckedKeys([])
  }
  
  // 加载权限树数据
  await loadPermissionTree()
  
  // 获取角色已有权限
  try {
    const response = await rolePermissionAPI.getRolePermissions({
      pageNum: 1,
      pageSize: 1000,
      roleId: row.id
    })
    if (response.success) {
      const rolePermissionIds = response.data.records.map(item => item.permissionId) || []
      checkedPermissions.value = rolePermissionIds
      
      // 等待下一个tick，确保树组件已经渲染完成，然后设置选中状态
      await nextTick()
      if (permissionTreeRef.value) {
        permissionTreeRef.value.setCheckedKeys(rolePermissionIds)
      }
    }
  } catch (error) {
    console.error('获取角色权限失败:', error)
    checkedPermissions.value = []
    if (permissionTreeRef.value) {
      permissionTreeRef.value.setCheckedKeys([])
    }
  }
  
  permissionDialogVisible.value = true
}

// 保存权限分配
const handleSavePermissions = async () => {
  try {
    permissionLoading.value = true
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    const allPermissionIds = [...checkedKeys, ...halfCheckedKeys]
    
    console.log('开始批量分配权限:', {
      roleId: currentRole.value.id,
      roleName: currentRole.value.name,
      permissionCount: allPermissionIds.length,
      permissionIds: allPermissionIds
    })
    
    // 使用优化的批量权限替换方法
    const response = await rolePermissionAPI.replaceRolePermissions(
      currentRole.value.id, 
      allPermissionIds
    )
    
    if (response.success) {
      ElMessage.success(`权限分配成功！共分配 ${allPermissionIds.length} 个权限`)
      permissionDialogVisible.value = false
      loadTableData()
    } else {
      ElMessage.error(response.message || '权限分配失败')
    }
  } catch (error) {
    console.error('权限分配失败:', error)
    ElMessage.error('权限分配失败: ' + (error.message || '未知错误'))
  } finally {
    permissionLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!roleFormRef.value) return
  
  try {
    await roleFormRef.value.validate()
    submitLoading.value = true
    
    let response
    if (dialogMode.value === 'add') {
      response = await roleAPI.createRole(roleForm)
      if (response.success) {
        ElMessage.success('角色创建成功')
      } else {
        ElMessage.error(response.message || '角色创建失败')
        return
      }
    } else {
      response = await roleAPI.updateRole(roleForm)
      if (response.success) {
        ElMessage.success('角色更新成功')
      } else {
        ElMessage.error(response.message || '角色更新失败')
        return
      }
    }
    
    dialogVisible.value = false
    loadTableData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置角色表单
const resetRoleForm = () => {
  Object.assign(roleForm, {
    id: null,
    name: '',
    code: '',
    description: '',
    status: 1
  })
  
  if (roleFormRef.value) {
    roleFormRef.value.clearValidate()
  }
}

// 填充角色表单
const fillRoleForm = (row) => {
  Object.assign(roleForm, {
    id: row.id,
    name: row.name,
    code: row.code,
    description: row.description,
    status: row.status
  })
}

// 获取角色操作列表
const getRoleActionList = (row) => {
  return [
    {
      command: 'view',
      label: '查看',
      icon: View,
      type: 'info'
    },
    {
      command: 'edit',
      label: '编辑',
      icon: Edit,
      type: 'primary'
    },
    {
      command: 'assign-permission',
      label: '分配权限',
      icon: Key,
      type: 'warning'
    },
    {
      command: 'delete',
      label: '删除',
      icon: Delete,
      type: 'danger',
      divided: true
    }
  ]
}

// 处理角色操作事件
const handleRoleAction = ({ command, row }) => {
  switch (command) {
    case 'view':
      handleView(row)
      break
    case 'edit':
      handleEdit(row)
      break
    case 'assign-permission':
      handleAssignPermission(row)
      break
    case 'delete':
      handleDelete(row)
      break
    default:
      console.warn('未知操作:', command)
  }
}

// 权限分配对话框关闭时的清理函数
const handlePermissionDialogClosed = () => {
  // 清空当前角色
  currentRole.value = null
  
  // 清空选中的权限
  checkedPermissions.value = []
  
  // 清空权限树的选中状态
  if (permissionTreeRef.value) {
    permissionTreeRef.value.setCheckedKeys([])
  }
  
  // 清空权限树数据（可选，减少内存占用）
  permissionTreeData.value = []
}

// 组件挂载时加载数据
onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
/* 复用用户管理的样式 */
.role-management {
  padding: 0;
  background: transparent;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.header-content h1.page-title {
  font-size: 24px;
  font-weight: 700;
  color: hsl(222.2 84% 4.9%);
  margin: 0 0 4px 0;
  line-height: 1.2;
}

.header-content p.page-description {
  color: hsl(215.4 16.3% 46.9%);
  font-size: 14px;
  margin: 0;
}

.header-actions .el-button {
  background: hsl(221.2 83.2% 53.3%);
  border: 1px solid hsl(221.2 83.2% 53.3%);
  color: hsl(210 40% 98%);
  font-weight: 500;
  border-radius: 6px;
}

.search-section {
  background: hsl(0 0% 100%);
  border: 1px solid hsl(214.3 31.8% 91.4%);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.status-select {
  width: 150px;
}

.table-section {
  background: hsl(0 0% 100%);
  border: 1px solid hsl(214.3 31.8% 91.4%);
  border-radius: 8px;
  overflow: hidden;
}

.role-table {
  width: 100%;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

.pagination-section {
  padding: 20px;
  display: flex;
  justify-content: center;
  border-top: 1px solid hsl(214.3 31.8% 91.4%);
}

.role-form .el-form-item {
  margin-bottom: 20px;
}

/* 权限分配样式 */
.permission-assignment {
  max-height: 400px;
  overflow-y: auto;
}

.role-info {
  background: hsl(210 40% 96%);
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 20px;
}

.role-info h4 {
  margin: 0 0 8px 0;
  color: hsl(222.2 84% 4.9%);
  font-size: 16px;
  font-weight: 600;
}

.role-info p {
  margin: 0;
  color: hsl(215.4 16.3% 46.9%);
  font-size: 14px;
}

.permission-tree {
  border: 1px solid hsl(214.3 31.8% 91.4%);
  border-radius: 6px;
  padding: 12px;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.node-label {
  font-weight: 500;
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .status-select {
    width: 100%;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>el-table>